﻿using System;
using System.ServiceModel.DomainServices.Client;
using System.Windows.Controls;
using System.Windows.Navigation;
using GradeApp.ViewModels;
using GradeApp.Web;
using GradeApp.Web.Services;

namespace GradeApp.Views
{
    public partial class AddNewCourse : Page
    {
        private GradeAppDomainContext _gradeAppDomainContext;

        public AddNewCourse()
        {
            _gradeAppDomainContext = new GradeAppDomainContext();
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void coursesDomainDataSource_LoadedData(object sender, LoadedDataEventArgs e)
        {

            if (e.HasError)
            {
                System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                e.MarkErrorAsHandled();
            }
        }

        private void AddNewCourseForm_EditEnded(object sender, DataFormEditEndedEventArgs e)
        {
            var currentItem = AddNewCourseForm.CurrentItem as Courses;
            currentItem.Id = Guid.NewGuid();

            var tutorCourses = new TutorCourses()
            {
                CourseId = currentItem.Id,
                TutorId = GradeAppContext.CurrentTutorId,
                IsOwner = true
            };
            var courseConfiguration = new CourseConfigurations { AbsencesAlarmPercent = 50, PointsAlarmPercent = 50, Id = Guid.NewGuid() };

            currentItem.TutorCourses.Add(tutorCourses);
            currentItem.CourseConfigurations = courseConfiguration;
            currentItem.CourseConfiguration_Id = courseConfiguration.Id;
            AddNewCourseForm.CommitEdit();
            coursesDomainDataSource.SubmitChanges();
            GradeAppContext.TryGetAllCourses();
        }

        private void AddNewCourseForm_DeletingItem(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //(AddNewCourseForm.CurrentItem as Courses)
            coursesDomainDataSource.SubmitChanges();
        }
    }
}
